package com.xxmw.transaction.conf.job;

import com.xxmw.transaction.common.excep.service.TransactionException;
import com.xxmw.transaction.common.utils.SpringContextUtil;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * 任务线程
 *
 * @author xiangzuotao
 * @date 2018年7月25日
 */
@Slf4j
@NoArgsConstructor
public class ScheduleJobRunnable implements Runnable {

    private Object target;

    private Method method;

    private String params;

    public ScheduleJobRunnable(String beanName, String methodName, String params) throws NoSuchMethodException, SecurityException {
        this.target = SpringContextUtil.getBean(beanName);
        this.params = params;
        if (StringUtils.isBlank(params)) {
            this.method = this.target.getClass().getDeclaredMethod(methodName);
        } else {
            this.method = this.target.getClass().getDeclaredMethod(methodName, String.class);
        }
    }

    @Override
    public void run() {
        try {
            ReflectionUtils.makeAccessible(method);
            if (StringUtils.isBlank(params)) {
                this.method.invoke(target);
            } else {
                this.method.invoke(target, params);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new TransactionException("执行定时任务失败");
        }
    }

}
